package com.joker.storehelper.client.android.storage;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joker.storehelper.client.android.CaptureActivity;
import com.joker.storehelper.client.android.PreferencesActivity;
import com.joker.storehelper.client.android.R;
import com.joker.storehelper.client.android.http.OkHttpUtil;
import com.joker.storehelper.client.android.lib.EndlessRecyclerOnScrollListener;

import java.io.IOException;
import java.util.List;

/**
 * Async goods list from backend
 * Created by Administrator on 2017/12/11.
 */

public class GoodsListFragment extends Fragment implements GoodsListAdapter.OnItemClickListener{

    private RecyclerView goodsView;
    private GoodsListAdapter adapter;
    private List<Goods> goodsList = Lists.newArrayList();
    private Handler handler;
    private String serverIp;
    private int pageNo = 0;
    private LinearLayoutManager layoutManager;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.goods,container,false);
        goodsView = view.findViewById(R.id.store_goods_list_id);
        goodsView.setHasFixedSize(true);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        serverIp = prefs.getString(PreferencesActivity.KEY_SERVER_IP, "13.125.86.228");
        getGoodsData();
        adapter = new GoodsListAdapter(getContext(),goodsList);
        layoutManager = new LinearLayoutManager(getContext());
        goodsView.setLayoutManager(layoutManager);
        goodsView.setAdapter(adapter);
        adapter.setItemClickListener(GoodsListFragment.this);
        goodsView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager){
            @Override
            public void onLoadMore(int currentPage) {
                getGoodsData();
            }
        });
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                adapter.nextPage(goodsList);
                pageNo++;
                return true;
            }
        });
        return view;
    }

    private void getGoodsData() {
        final String url = "http://" + serverIp + "/api/list?page=" + pageNo;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject data = OkHttpUtil.getJSON(url);
                    Log.i("Goods", data.toString());
                    goodsList = JSON.parseArray(data.getJSONArray("data").toJSONString(), Goods.class);
                    if(goodsList == null){
                        return;
                    }
                    Message message = handler.obtainMessage();
                    handler.sendMessage(message);
                } catch (IOException e) {
                    Log.getStackTraceString(e);
                }
            }
        }).start();
    }

    @Override
    public void onItemClick(int position){
        FragmentActivity activity = getActivity();
        if(activity != null){
            Goods g = adapter.getItem(position);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.putExtra("goodsId", g.getId());
            intent.putExtra("mode", 1);
            intent.setClassName(activity, CaptureActivity.class.getName());
            startActivity(intent);
        }
    }
}
